/*
 *   Copyright 1999-2016 Asiainfo Technologies(China),Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.asiainfo.redis.service.busidatawriter;

import com.asiainfo.redis.service.BusiConfigService;
import redis.clients.util.SafeEncoder;

import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @version v 1.0 on 2016/7/27 18:47
 * @auther william.xu
 */
public class BusiDataRedisWriter4ThreeMoreConditionsSaveUniqueKeyValue extends BusiDataRedisWriter {

    public BusiDataRedisWriter4ThreeMoreConditionsSaveUniqueKeyValue(Integer operFlag) {
        super(operFlag);
    }

    @Override
    public void doWrite(ResultSet rst) throws Exception {
        String busiTypeCode = busiTypeRepository.findOne(busiDataRule.getBusiTypeId()).getBusiCode();
        String keyPrefix = busiDataRule.getKeyPrefix();
        String uniqueField = busiDataRule.getUniqueField();
        String[] saveFields = busiDataRule.getSaveFields().split(BusiConfigService.SPLIT_CODE);
        while (rst.next()) {
            String uniqueFieldValue = rst.getObject(uniqueField).toString();
            byte[] key = SafeEncoder.encode(busiTypeCode+":"+keyPrefix+":"+uniqueFieldValue);
            Map row = new HashMap();
            for (String saveField : saveFields) {
                row.put(saveField, rst.getObject(saveField));
            }
            connection.set(key, SafeEncoder.encode(object2String(row)));
        }

    }
}
